# -*- coding: utf-8 -*-
import random
from MySQLdb import *
from settings import db

def getAttrType(attrName):
    result = db.sqlQuery(
        'SELECT attribute_id, backend_type FROM magento.firsteav_attribute where attribute_code like \'%' + attrName + '%\' and entity_type_id=4;')
    if not result:
        return False, False
    return result[0][0], result[0][1]


def getProductsNameByAttrId(attrId, attrType):
    productsName = []
    productsId = db.sqlQuery(
        'SELECT entity_id FROM magento.firstcatalog_product_entity_' + attrType + ' where attribute_id=' + str(attrId)
        + ' and entity_id in (SELECT entity_id FROM magento.firstcatalog_product_entity_int where attribute_id=(SELECT attribute_id FROM magento.firsteav_attribute where attribute_code=\'status\') and value=1);')
    for productId in productsId:
        result = db.sqlQuery("""SELECT value FROM magento.firstcatalog_product_entity_varchar
        where attribute_id=(SELECT attribute_id FROM magento.firsteav_attribute where attribute_code='name' and entity_type_id=4)
        and entity_id = """ + str(productId[0]))
        productsName.append(result[0][0])
    return productsName


def searchProductsByAttr(attrName):
    attrId, attrType = getAttrType(attrName)
    if attrId and attrType:
        productsName = getProductsNameByAttrId(attrId, attrType)
    return productsName